package com.joolun.framework.socket;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import com.joolun.common.core.redis.RedisCache;
import com.joolun.common.utils.StringUtils;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;



/**
 * @ClassNameSocketIOHandler
 * @Author DELL
 * @Version 1.0
 **/
@Component
public class SocketIOHandler {

    private static final Logger log = LoggerFactory.getLogger(SocketIOHandler.class);

    @Resource
    private ClientCache clientCache;

    @Resource
    private RedisCache redisCache;


    /**
     * @return void
     * @Author 二哈老头子
     * @Description 客户端连接的时候触发，前端js触发：socket = io.connect("http://localhost:9092");
     * 添加connect事件，当客户端发起连接时调用，本文中将clientId与sessionId存入
     * @Date 12:12 2022/1/20
     * @Param [client]
     **/
    @OnConnect
    public void onConnect(SocketIOClient client) {
        String clientId = client.getHandshakeData().getSingleUrlParam("clientId");
        clientCache.saveClient(clientId, client);
        client.sendEvent("connected", "节点id = " + clientId);
        //修改节点状态为 在线
    }


    /**
     * @return void
     * @Author chenbinbin
     * @Description 客户端关闭连接或超时时触发：前端js触发：socket.disconnect();
     * @Date 12:14 2022/1/20
     * @Param [client]
     **/
    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {

        //1  断开连接了
        String clientId = client.getHandshakeData().getSingleUrlParam("clientId");
        clientCache.deleteUserCacheByUserId(clientId);
        log.info("-----------客户端断开连接===== " + clientId);
    }

    /**
     * @return void
     * @Author chenbinbin
     * @Description 消息接收入口，当接收到消息后，查找发送目标客户端，并且向该客户端发送消息，且给自己发送消息
     * @Date 13:51 2022/1/20
     * @Param [client, request, data]
     **/
    @OnEvent("pushNodeInfoEvent")
    public void pushNodeInfoEvent(SocketIOClient client, AckRequest ackRequest, String data) throws Exception {
        log.info("----------socket监听到数据----------------------" + data);
        if(StringUtils.isEmpty(data)){
            log.info("----------socket监听到空数据直接返回----------------------" + data);
            return;
        }
    }




}
